package com.atguigu.gulimall.order.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.enume.OrderStatusEnum;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WmsFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    private ThreadLocal<OrderSubmitVo> submitVoThreadLocal = new ThreadLocal<>();


    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private CartFeignService cartFeignService;
    @Autowired
    private ThreadPoolExecutor executor;
    @Autowired
    private WmsFeignService wmsFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.threadLocal.get();
        //System.out.println("主线程。。。"+Thread.currentThread().getId());
        //为了保证异步调用请头头不会丢失，需要设置到每个异步线程里面去
        //获取之前的请求
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            //1、远程查询所有的收货地址列表
            //System.out.println("member线程。。。"+Thread.currentThread().getId());
            //每一个线程都来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            confirmVo.setAddress(address);
        }, executor);


        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //2、远程查询购物车所有选中购物项
            //System.out.println("cart线程。。。"+Thread.currentThread().getId());
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> items = cartFeignService.getCurrentUserItems();
            confirmVo.setItems(items);
            //feign在远程调用之前要构造请求，调用很多的拦截器
            //RequestInterceptor interceptor : requestInterceptors
        }, executor).thenRunAsync(() -> {
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> skuIds = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            // TODO: 2022/8/3 一定要启动库存服务，否则库存查不出来
            R hasStock = wmsFeignService.getSkusHasStock(skuIds);
            List<SkuHasStockVo> data = hasStock.getData(new TypeReference<List<SkuHasStockVo>>() {
            });
            if (data != null) {
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
                confirmVo.setStocks(map);
            }
        }, executor);


        //3、查询用户积分
        Integer integration = memberRespVo.getIntegration();
        confirmVo.setIntegration(integration);

        //4、其他数据自动计算
        //todo 5、防重令牌
        String token = IdUtil.fastSimpleUUID();
        //页面带一个令牌，服务器存一个
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(), token, 30, TimeUnit.MINUTES);
        confirmVo.setOrderToken(token);
        CompletableFuture.allOf(getAddressFuture, cartFuture).get();
        return confirmVo;
    }
    //同一个对象内事物方法互调 默认是失效的，原因是绕过了代理对象
    //事物是用代理对象来控制的
    @Transactional(timeout = 30)
    public void a(){
        //springboot中的坑
        //如果是这种情况 b c 做任何设置都没用，都是和a共用一个事物
        //aService.a();  bService.b();  这种是可以的
        OrderServiceImpl orderService = (OrderServiceImpl) AopContext.currentProxy();
        orderService.b();
        orderService.c();
        //b c两种相当于提取的两个方法
        b();    //和a共用一个事物，会回滚  timeout以a为主，b中设置失效
        c();  //新开一个事物，这个例子中c不会回滚
        int i = 10 / 0;
    }
    @Transactional(propagation = Propagation.REQUIRED,timeout = 2)
    public void b(){

    }
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void c(){

    }











    //本地事物，在分布式系统下，只能控制住自己的回滚，控制不了其他服务的回滚
    //分布式事物  ：最大问题，网路问题+分布式机器
    //@Transactional(isolation = Isolation.REPEATABLE_READ) 隔离级别设置
    //@GlobalTransactional //seata使用 ,这里是高并发场景不适合使用seata，加锁会导致整个业务逻辑编程串行化
    @Transactional  //方法自己也是一个事物，需要加上本地事物
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        //当前请求传过来的数据放到ThreadLocal中方便下面使用
        submitVoThreadLocal.set(vo);
        SubmitOrderResponseVo response = new SubmitOrderResponseVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.threadLocal.get();
        response.setCode(0);
        //1、验证令牌【令牌的对比和删除必须保证原子性】
        //返回0--删除失败  1--删除成功
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
        String redisKey = OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId();
        /**
         *
         * 1、参数一构造脚本
         * 2、redis中的key
         * 3、需要对比的值
         */
        //原子验证令牌和删除令牌
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(redisKey), orderToken);
        if (result == 0L) {
            //令牌验证失败
            response.setCode(1);
            return response;
        } else {
            //令牌验证成功
            //下单：创建订单，验令牌，验价格，锁库存
            //1、创建订单，订单项等信息
            OrderCreateTo order = createOrder();


            //2、验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                // 金额对比，相差0.01是可以接受范围

                //todo 3、保存订单
                saveOrder(order);
                //4、锁定库存 只要有异常回滚订单数据
                //    订单号，所有订单项（sku_id，sku_name，stock_locked）
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());
                    return itemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(locks);
                // TODO 4、 远程锁库存
                    //扣库存成功了，但是网路原因超时了，还是订单回滚，订单不回滚
                //为了保证高并发，
                // 库存服务自己回滚。 可以发消息给库存服务
                //库存服务本身可以使用自动解锁模式 消息队列
                R r = wmsFeignService.orderLockStock(lockVo);

                if (r.getCode() == 0) {
                    //    锁成功了
                    response.setOrder(order.getOrder());
                    // TODO 5、远程扣减积分
                    //int i = 10 / 0;  //订单回滚库存不回滚
                    // TODO: 2022/8/9  订单创建成功发送下消息给MQ
                    try {
                        // TODO: 2022/8/10 保证消息一定会发送出去，每一个消息都可以做好日志记录（给数据库保存一个详细的信息）
                        // TODO: 2022/8/10 定期扫描数据库，将失败的消息再发送一次
                        rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
                    } catch (AmqpException e) {
                        // TODO: 2022/8/10  将没发送的消息进行重试发送
                    }

                    return response;
                } else {
                    //    锁失败了
                    response.setCode(3);
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                    //return response;
                }

            } else {
                response.setCode(2);
                return response;
            }


        }
        //服务器令牌
        //String redisToken = redisTemplate.opsForValue().get(redisKey);
        //if (redisToken != null && orderToken.equals(redisToken)) {
        //// 令牌验证通过
        //    redisTemplate.delete(redisKey);
        //}else {
        //// 不通过
        //}
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {

        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order_sn;
    }

    @Override
    public void closeOrder(OrderEntity entity) {
        //查询这个订单当前的最新状态
        OrderEntity orderEntity = this.getById(entity.getId());
        if (orderEntity.getStatus()== OrderStatusEnum.CREATE_NEW.getCode().intValue()) {
            OrderEntity update = new OrderEntity();
            update.setId(entity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            //关单，只需要修改订单的状态为已取消
            this.updateById(update);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);


            //发给MQ一个 订单的交换机==》库存的队列
            rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
        }

    }
    /**
     * 获取当前订单的支付信息
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity order = this.getOrderByOrderSn(orderSn);
        //这里支付宝要求的输入框的精度是2位，数据库是4位这里需要做处理
        BigDecimal bigDecimal = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        //应付金额
        payVo.setTotal_amount(bigDecimal.toString());
        //订单号
        payVo.setOut_trade_no(order.getOrderSn());
        List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        //订单标题
        OrderItemEntity item = itemEntities.get(0);
        payVo.setSubject(item.getSkuName());
        //备注，这里设置成销售属性
        payVo.setBody(item.getSkuAttrsVals());
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.threadLocal.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                //按照降序排列，最上面是最新的订单
                new QueryWrapper<OrderEntity>().eq("member_id",memberRespVo.getId()).orderByDesc("id")
        );
        List<OrderEntity> collect = page.getRecords().stream().map(order -> {
           // 根据订单号查出所有的订单项
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemEntities);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(collect);

        return new PageUtils(page);
    }

    /**
     * 1、处理支付宝的支付结果
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //1、保存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity
        	.setOrderSn(vo.getOut_trade_no())
        	.setAlipayTradeNo(vo.getTrade_no())
        	.setTotalAmount(new BigDecimal(vo.getTotal_amount()))
        	.setSubject(vo.getSubject())
        	.setPaymentStatus(vo.getTrade_status())
        	.setCreateTime(vo.getGmt_create())
        	.setConfirmTime(vo.getGmt_payment())
        	.setCallbackContent(vo.getBody())
        	.setCallbackTime(vo.getNotify_time())
        	;
        paymentInfoService.save(infoEntity);

        //2、修改订单的状态信息
       if (vo.getTrade_status().equals("TRADE_SUCCESS")||vo.getTrade_status().equals("TRADE_FINISHED")){
          baseMapper.updateOrderStatus(vo.getOut_trade_no(), OrderStatusEnum.PAYED.getCode());
       }
        return "success";

    }

    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrder) {
        // TODO: 2022/8/20  保存订单信息
        //1、保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        String orderSn = seckillOrder.getOrderSn();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(seckillOrder.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        Integer num = seckillOrder.getNum();
        BigDecimal amount = (seckillOrder.getSeckillPrice()).multiply(new BigDecimal("" + num));
        orderEntity.setPayAmount(amount);
        orderEntity.setCreateTime(new Date());
        this.save(orderEntity);

        //todo 2、保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(orderSn);
        orderItemEntity.setRealAmount(amount);
        orderItemEntity.setSkuQuantity(num);
        orderItemService.save(orderItemEntity);
    }

    /**
     * 保存订单数据
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setCreateTime(new Date());
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);

    }

    /**
     * 创建订单
     *
     * @return
     */
    private OrderCreateTo createOrder() {
        OrderCreateTo createTo = new OrderCreateTo();
        //1、生成订单号
        String orderSn = IdWorker.getTimeId();
        //创建订单号
        OrderEntity orderEntity = buildOrder(orderSn);

        //2、获取到所有的订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);

        //3、计算价格,积分等相关信息
        computePrice(orderEntity, itemEntities);

        createTo.setOrder(orderEntity);
        createTo.setOrderItems(itemEntities);


        return createTo;

    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        //1、订单总额，叠加每一个订单项的总额信息
        BigDecimal total = new BigDecimal("0");
        BigDecimal coupon = new BigDecimal("0");
        BigDecimal integration = new BigDecimal("0");
        BigDecimal promotion = new BigDecimal("0");
        BigDecimal giftIntegration = new BigDecimal("0");
        BigDecimal giftGrowth = new BigDecimal("0");

        for (OrderItemEntity entity : itemEntities) {
            //订单总额是已经在订单项表里面减去了三项优惠
            total = total.add(entity.getRealAmount());
            //把这三项优惠累加起来，设置到订单表里面去
            coupon = coupon.add(entity.getCouponAmount());
            integration = integration.add(entity.getIntegrationAmount());
            promotion = promotion.add(entity.getPromotionAmount());
            giftIntegration = giftIntegration.add(new BigDecimal(entity.getGiftIntegration().toString()));
            giftGrowth = giftGrowth.add(new BigDecimal(entity.getGiftGrowth().toString()));
        }
        //  1、订单价格相关
        orderEntity.setTotalAmount(total);
        // 应付金额   订单总额+运费
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        // 设置优惠信息
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);

        //设置积分和成长值
        orderEntity.setIntegration(giftIntegration.intValue());
        orderEntity.setGrowth(giftGrowth.intValue());
        //未删除
        orderEntity.setDeleteStatus(0);


    }

    /**
     * 构建订单
     *
     * @param orderSn
     */
    private OrderEntity buildOrder(String orderSn) {
        MemberRespVo memberRespVo = LoginUserInterceptor.threadLocal.get();
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        entity.setMemberId(memberRespVo.getId());

        OrderSubmitVo submitVo = submitVoThreadLocal.get();
        //获取收货信息
        R fare = wmsFeignService.getFare(submitVo.getAddrId());
        FareVo fareResp = fare.getData(new TypeReference<FareVo>() {
        });
        //设置运费
        entity.setFreightAmount(fareResp.getFare())
                //设置收货人信息
                .setReceiverProvince(fareResp.getAddress().getProvince())
                .setReceiverCity(fareResp.getAddress().getCity())
                .setReceiverRegion(fareResp.getAddress().getRegion())
                .setReceiverDetailAddress(fareResp.getAddress().getDetailAddress())
                .setReceiverName(fareResp.getAddress().getName())
                .setReceiverPhone(fareResp.getAddress().getPhone())
                .setReceiverPostCode(fareResp.getAddress().getPostCode());

        //设置订单的相关状态信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);
        return entity;
    }

    /**
     * 构建所有订单项数据
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //最后确定每个购物项的价格
        List<OrderItemVo> currentUserItems = cartFeignService.getCurrentUserItems();
        if (currentUserItems != null && currentUserItems.size() > 0) {
            List<OrderItemEntity> itemEntities = currentUserItems.stream().map(cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    /**
     * 构建某一个订单项
     *
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //1、订单信息：订单号  √
        //2、商品的spu信息 √
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        itemEntity.setSpuId(data.getId());
        itemEntity.setSpuName(data.getSpuName());
        //品牌这里直接用品牌id封装
        itemEntity.setSpuBrand(data.getBrandId().toString());
        itemEntity.setCategoryId(data.getCatalogId());
        //图片没有做封装

        //3、商品的sku信息  √
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        //销售属性组合
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        //4、优惠信息【不做】
        //5、积分信息
        //成长值 //赠送积分
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        //6、订单项的价格信息(这里三种优惠写死了，实际情况需要查询)
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单项的实际金额(总额-各种优惠项)
        BigDecimal origin = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal subtract = origin.subtract(itemEntity.getPromotionAmount()).subtract(itemEntity.getCouponAmount()).subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(subtract);
        return itemEntity;
    }

}